package com.baizhi.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("user")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    // 服务注册与发现的客户端对象
    @Autowired
    private DiscoveryClient discoveryClient;

    // 负载均衡客户端对象
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping
    public String invokeDemo() {
        log.info("user demo ...");

        // 1.调用订单服务，直接使用url地址请求
//        RestTemplate restTemplate = new RestTemplate();
//        String orderResult = restTemplate.getForObject("http://"+randomHost()+"/order", String.class);

        // 2.使用Ribbon组件+RestTemplate实现负载均衡调用
//        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("ORDERS");
//        serviceInstances.forEach(serviceInstance ->
//            log.info("服务主机：{}, 服务端口：{}, 服务地址：{}", serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getUri())
//        );
//        String orderResult = new RestTemplate().getForObject(serviceInstances.get(0).getUri() + "/order", String.class);

        // 3.使用LoadBalancerClient进行服务调用
//        ServiceInstance serviceInstance = loadBalancerClient.choose("ORDERS");  // 默认轮询策略
//        log.info("服务主机：{}, 服务端口：{}, 服务地址：{}", serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getUri());
//        String orderResult = restTemplate.getForObject(serviceInstance.getUri() + "/order", String.class);

        // 4.使用@LoadBalanced注解，让对象具有Ribbon负载均衡特性
        String orderResult = restTemplate.getForObject("http://ORDERS/order", String.class);

        log.info("调用订单服务成功：{}", orderResult);
        return "调用order服务成功，结果为：" + orderResult;
    }

    // 自定义随机策略
    public String randomHost() {
        List<String> hosts = new ArrayList<>();
        hosts.add("localhost:9999");
        hosts.add("localhost:9990");
        // 生成随机策略
        int index = new Random().nextInt(hosts.size());
        return hosts.get(index);
    }
}
